package com.graduation.check.config;

import com.graduation.check.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    @Autowired
    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {

        try {
            String jwt = extractTokenFromRequest(request);
            
            // 添加调试日志
            logger.debug("========== JWT认证开始 ==========");
            logger.debug("请求路径: " + request.getRequestURI());
            logger.debug("请求方法: " + request.getMethod());
            logger.debug("Authorization Header: " + request.getHeader("Authorization"));
            logger.debug("提取的Token: " + (jwt != null ? jwt.substring(0, Math.min(20, jwt.length())) + "..." : "null"));

            if (jwt != null) {
                String username = jwtUtil.extractUsername(jwt);
                logger.debug("从Token中提取的用户名: " + username);

                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    logger.debug("加载的用户信息: " + userDetails.getUsername());
                    logger.debug("用户权限: " + userDetails.getAuthorities());

                    if (jwtUtil.validateToken(jwt, userDetails)) {
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(
                                        userDetails,
                                        null,
                                        userDetails.getAuthorities()
                                );
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        logger.debug("JWT认证成功，已设置 SecurityContext");
                    } else {
                        logger.warn("JWT Token验证失败");
                    }
                } else {
                    if (username == null) {
                        logger.warn("无法从Token中提取用户名");
                    }
                    if (SecurityContextHolder.getContext().getAuthentication() != null) {
                        logger.debug("已存在认证信息，跳过");
                    }
                }
            } else {
                logger.debug("未找到JWT Token");
            }
            logger.debug("========== JWT认证结束 ==========\n");
        } catch (Exception e) {
            logger.error("JWT认证失败: " + e.getMessage(), e);
        }

        filterChain.doFilter(request, response);
    }

    private String extractTokenFromRequest(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            return authorizationHeader.substring(7);
        }
        return null;
    }
}